#
# @lc app=leetcode.cn id=592 lang=python3
#
# [592] 分数加减运算
#

# @lc code=start
class Solution:
    def fractionAddition(self, expression: str) -> str:
        n, idx = len(expression), 0
        numerator, denominator = 0, 1
        while idx < n:
            sign = 1
            if expression[idx] == '-' or expression[idx] == '+':
                sign = 1 if expression[idx] == '+' else -1
                idx += 1
            num = 0
            while idx < n and expression[idx].isdigit():
                num = num * 10 + int(expression[idx])
                idx += 1
            num *= sign
            idx += 1
            den = 0
            while idx < n and expression[idx].isdigit():
                den = den * 10 + int(expression[idx])
                idx += 1
            numerator = numerator * den + num * denominator
            denominator *= den

        if numerator == 0:
            return '0/1'
        g = gcd(abs(numerator), denominator)

        return str(numerator // g) + '/' + str(denominator // g)

# @lc code=end
